package com.wing.cms.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wing.cms.dao.ChannelDao;
import com.wing.cms.dao.PlaceholderDao;
import com.wing.cms.domain.Placeholder;
import com.wing.common.util.GUID;
import com.wing.common.util.PageBean;

/**
 * 
 * @author wyf
 * 
 */
@Service
@Transactional
public class PlaceholderManager {
	@Autowired
	private PlaceholderDao placeholderdao;
	@Autowired
	private ChannelDao channelDao;

	/**
	 * 获得该对象所有数据的列表
	 * 
	 * @return list
	 */
	public List<Map<String, Object>> findAll() {
		return placeholderdao.findAll();
	}

	public PageBean findPageList(int currentPage, int pageSize) {
		return placeholderdao.findPageList(currentPage, pageSize);
	}

	/**
	 * 通过id得到对象
	 *
	 * @param  id
	 * @return pObject
	 */
	public Placeholder findById(String id) {
		return placeholderdao.findById(id);
	}

	/**
	 * 保存对象
	 *
	 * @param  placeholder
	 */
	public void savePlaceholder(Placeholder placeholder) {
		if (placeholder.getId() == null || "".equals(placeholder.getId())) {
			placeholder.setId(new GUID().toString());
			placeholderdao.insert(placeholder);
		} else {
			placeholderdao.update(placeholder);
		}
	}

	/**
	 * 编辑对象
	 *
	 * @param  placeholder
	 */
	public void updatePlaceholder(Placeholder placeholder) {
		placeholderdao.update(placeholder);
	}

	/**
	 * 删除对象
	 *
	 * @param  chk 对象id数组
	 */
	public void deletePlaceholders(String[] chk) {
		for (int i = 0; i < chk.length; i++) {
			placeholderdao.delete(chk[i]);
		}
	}

	public List<Map<String, Object>> findPortletIdListByPageAndHoder(String pageId, String hoderId) {
		String layId = null;
		if(pageId.indexOf("a,")!= -1){
			//虚拟的布局id,布局文件已经写死article.jsp
			 layId = "articleLayId";
		}else if(pageId.indexOf("p,")!= -1){
			//虚拟的布局id,布局文件已经写死product.jsp
			 layId = "productayId";
		}else{
			 layId = channelDao.findById(pageId).getLayout();
		}
		return placeholderdao.findPortletIdByAssociateId(pageId,hoderId, layId);
	}
	
	public  void  savePortletNewPlace(String column_id,String column_array) {
		String[] portletIdArray = column_array.split(",");
		column_id = column_id.substring(7,column_id.length());
		int order_num = 10;
		for(String portletId:portletIdArray){
			order_num++;
			if(portletId==null || portletId.equals(""))continue;
			placeholderdao.updatePlace(column_id,portletId,order_num);
		}
	}
}
